//
//  QieHViewController.m
//  Estate
//
//  Created by heyong on 16/5/30.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "QieHViewController.h"
#import "ProjectModel.h"
//#import "HZStatusBarEffect/HZStatureEffect.h"
#import "NSString+Extension.h"
#import "TTProjectQieHCell.h"

@interface QieHViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSArray *textArr;
}

@property (strong, nonatomic)FMDatabase *db;
@property (strong, nonatomic)NSMutableArray *projectDataArray;
@property (strong, nonatomic)UITableView *tableView;
@property(copy, nonatomic)NSString *_dePro;

@end

@implementation QieHViewController
- (ProjectChangeHeaderView *)headView{
    if(!_headView){
        _headView=[[ProjectChangeHeaderView alloc]initWithFrame:CGRECTS(0, 44, 375, 120)];
    }
    return _headView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRECTS(0, 120+44, 375, 517)style:UITableViewStyleGrouped];
        _tableView.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
        [_tableView registerNib:[UINib nibWithNibName:@"TTProjectQieHCell" bundle:nil] forCellReuseIdentifier:@"TTProjectQieHCell"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

-(personRoleView *)roleView{
    if (!_roleView) {
        _roleView = [[personRoleView alloc]initWithFrame:self.view.bounds];
        _roleView.backgroundColor=[[UIColor blackColor]colorWithAlphaComponent:0.4];
        _roleView.layer.cornerRadius = 5;
    }
    return _roleView;
}

- (NSMutableArray *)projectDataArray{
    if(_projectDataArray==nil){
        _projectDataArray=[NSMutableArray array];
    }
    return _projectDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"项目切换";
    self.view.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    [self loadData];
    [self.view addSubview: self.headView];
    [self.view addSubview:self.tableView];
}

#pragma  mark-加载数据
- (void)loadData {
    personModel *model=[[personModel alloc]init];
    model.projectName = DEF_PERSISTENT_GET_OBJECT(@"proname");
    self.indexProName = model.projectName;
    model.headImagePath=@"";
    //用户名
    NSString *name = DEF_PERSISTENT_GET_OBJECT(@"realname");
    model.name = name;
    
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    model.position = role;
    self.headView.model = model;
    
    //数据库查询
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    //根据id查询到项目
    NSArray *proIdArr;
    @try {
        proIdArr=[helper DataBase:db selectStr:@"distinct(PRO_ID),*" selectKeyTypes:@{@"PRO_ID":@"text"} fromTable:PROJECT_USER whereCondition:@{@"USER_ID":USERID}];
        
    } @catch (NSException *exception) {
        NSLog(@"error:%@",exception);
        
    } @finally {
        
    }
    
    //查询相关联的巡检项目
    NSMutableArray *proIds= [LSUtility quertProIdByInspectId:USERID];
    for (NSDictionary *proDic in proIdArr){
        NSString *proId = proDic[@"PRO_ID"];
        [proIds addObject:proId];
    }
    
    //id 去重
    proIds =[proIds valueForKeyPath:@"@distinctUnionOfObjects.self"];
    //根据项目id查询项目名称
    for (int i=0; i<proIds.count; i++) {
        NSString *proId=[proIds objectAtIndex:i];
        //根据id查项目名
        NSArray *arr= [helper DataBase:db selectStr:@"*" selectKeyTypes:@{@"PROJECT_NAME":@"text",@"PROJECT_TYPE":@"text"} fromTable:PROJECT whereCondition:@{@"ID":proId}];
        if(arr.count>0){
            NSDictionary *proName = arr[0];
            NSLog(@"%@",proName);
            ProjectModel *model=[[ProjectModel alloc]init];
            model.projectId=proId;
            model.projectName = proName[@"PROJECT_NAME"];
            model.projectType = proName[@"PROJECT_TYPE"];

            [self.projectDataArray addObject:model];
        }
    }
    
    [self.tableView reloadData];
}

#pragma mark -UITabkeViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.projectDataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(self.indexProName ){
        return  40;
        
    }else{
        return 0.001;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

#pragma mark -UITabeleDataSourse
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TTProjectQieHCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TTProjectQieHCell"];
    //设置文字
    ProjectModel *model = self.projectDataArray[indexPath.row];
    cell.nameLabel.text = model.projectName;
    //默认选择项
    if([self.indexProName isEqualToString:cell.nameLabel.text]){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //设置文字
    ProjectModel *model = self.projectDataArray[indexPath.row];
    CGFloat cellHeight = 44*BIZ;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width-20;
    cellHeight = [model.projectName boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height+30;
    if(cellHeight<=44*BIZ){
        cellHeight=44*BIZ;
    }
    return cellHeight;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(self.indexProName ){
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor=[UIColor colorWithRed:0.17 green:0.56 blue:0.55 alpha:1.00];
        titleLabel.text=[self.indexProName isEqualToString:@""]?@"  项目切换":[NSString stringWithFormat:@"  %@",self.indexProName];
        
        return titleLabel;
    }else{
        return nil;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //判断当前项目是否签到签退。如果是允许切换项目
    BOOL qiehuan=[LSUtility projectChangingBySignIn];
    if(qiehuan){
        WEAKSELF
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        // 更改项目id
        ProjectModel *model = self.projectDataArray[indexPath.row];
        
        NSArray *typeArr = [NSArray array];
        // 点击的是当前项目
        if ([model.projectId isEqualToString:PROID] && ![model.projectId isEqualToString:@"LEADER_01"]) {
            NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
            // 判断身份类型  查询项目人员表
            NSMutableArray *types = [LSUtility getIdentitysByUserId:USERID andProId:model.projectId andUserType:role];

            typeArr = [self whetherHavePage:types];
            
            // 点击的是领导项 或者分管领导
        } else if ([model.projectId isEqualToString:@"LEADER_01"]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            // 赋值类型
            NSString *type = @"LEADER_01";
            //初始化完成 跳转
            EsTabBarController *tabMain=[[EsTabBarController alloc]init];
            [tabMain setProId:PROID setProType:PROTYPE andUserId:USERID andRole:type];
            [[UIApplication sharedApplication].delegate window].rootViewController = tabMain;
            
            [weakSelf changeProjectSuccess:type];
            // 点击的不是当前项目
        } else {
        
            DEF_PERSISTENT_SET_OBJECT(model.projectId, @"proid");
            DEF_PERSISTENT_SET_OBJECT(model.projectName, @"proname");
            DEF_PERSISTENT_SET_OBJECT(model.projectType, @"proType");
            //  判断身份类型  查询项目人员表
            NSMutableArray *types = [LSUtility getIdentitysByUserId:USERID andProId:model.projectId andUserType:@""];
            typeArr = [self whetherHavePage:types];
        }
        
        // 大于两个角色
        if (typeArr.count > 1) {
            [self.view addSubview:self.roleView];
            //设置用户名
            self.roleView.userName.text=[NSString stringWithFormat:@"  %@",DEF_PERSISTENT_GET_OBJECT(@"realname")];
            [self.roleView.dataArray removeAllObjects];
            self.roleView.dataArray = (NSMutableArray *)typeArr;
            //点击确定
            self.roleView.sureBlock=^(NSDictionary *roleOrPro){
                if(!roleOrPro){
                    [LSUtility showToastWithMessage:@"请选择角色" inView:weakSelf.view Andtime:1.];
                    return ;
                }
                // 获取点击的用户类型
                NSString *type = roleOrPro[@"userType"];
                [weakSelf.roleView removeFromSuperview];
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
                //初始化完成 跳转
                EsTabBarController *tabMain=[[EsTabBarController alloc]init];
                [tabMain setProId:PROID setProType:PROTYPE andUserId:USERID andRole:type];
                [[UIApplication sharedApplication].delegate window].rootViewController = tabMain;
                weakSelf.roleView=nil;
                [weakSelf changeProjectSuccess:type];
            };
            // 点击取消
            self.roleView.cancelBlock=^{
                [weakSelf.roleView removeFromSuperview];
                weakSelf.roleView=nil;
            };
            
            // 等于两个角色
        } else if (typeArr.count == 1) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            // 获取用户类型
            NSDictionary *roleOrPro = typeArr[0];
            NSString *type = roleOrPro[@"userType"];
            //初始化完成 跳转
            EsTabBarController *tabMain=[[EsTabBarController alloc]init];
            [tabMain setProId:PROID setProType:PROTYPE andUserId:USERID andRole:type];
            [[UIApplication sharedApplication].delegate window].rootViewController = tabMain;
            
            [weakSelf changeProjectSuccess:type];
            // 只有一个角色
        } else {
            return;
        }
        
        self.indexProName = model.projectName;
        [self refresh];
        
    }else{
        [LSUtility showToastWithMessage:@"当前项目未签退,不能切换项目。" inView:self.view Andtime:1.5];
    }
}

// 判断角色是否有页面
- (NSArray *)whetherHavePage:(NSArray *)typeArr {
    
    NSMutableArray *typeMutabelArr = [NSMutableArray array];
    for (NSDictionary *typeDic in typeArr) {
        //判断该角色是否有页面
        NSString *type = typeDic[@"userType"];
        if([USERTYPE.userTypeArray containsObject:type]){
            [typeMutabelArr addObject:typeDic];
        }
    }
    return typeMutabelArr;
}

// 项目切换成功
- (void)changeProjectSuccess:(NSString *)role {

    NSString *path = [NSString getPathWith:@"/standardClass.plist"];
    NSString *path1 = [NSString getPathWith:@"/standardKey.plist"];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:path];
    if (blHave) {
        [[NSFileManager defaultManager]  removeItemAtPath:path error:nil];
    }
    BOOL blHave1=[[NSFileManager defaultManager] fileExistsAtPath:path1];
    if (blHave1) {
        [[NSFileManager defaultManager]  removeItemAtPath:path1 error:nil];
    }
    
    NSString *roleName;
    if([role isEqualToString:@"1"]) {//巡检组长
        roleName=@"巡检组长";
        
    }else if ([role isEqualToString:@"2"]) {//巡检员
        roleName=@"巡检员";
        
    }else if([role isEqualToString:@"USER_01"]) { //总监
        roleName=@"总监";
        
    }else if([role isEqualToString:@"USER_03"]) { //监理
        roleName=@"监理员";
        
    }else if([role isEqualToString:@"USER_07"]) { //专业监理
        roleName=@"专业监理工程师";
        
    }else if([role isEqualToString:@"CONSTRACT_01"]||[role isEqualToString:@"CONSTRACT_02"]||[role isEqualToString:@"CONSTRACT_03"]||[role isEqualToString:@"CONSTRACT_04"]||[role isEqualToString:@"CONSTRACT_05"]||[role isEqualToString:@"CONSTRACT_06"]||[role isEqualToString:@"CONSTRACT_07"]){   //施工方
        roleName=@"施工方";
        
    }else if([role isEqualToString:@"LEADER_01"]){//领导
        roleName = @"领导";
        
    }else if ([role isEqualToString:@"USER_05"]){
        roleName=@"日志工程师";
    }
    else if ([role isEqualToString:@"USER_04"]){
        roleName=@"监理安全工程师";
        
    } else if ([role isEqualToString:@"BUILD_01"]){
        roleName=@"单位领导";
        
    }else if ([role isEqualToString:@"BUILD_02"]){
        roleName=@"建设单位工程部";
        
    }else if([role isEqualToString:@"USER_02"]){
        roleName=@"副总监";
    } else if ([role isEqualToString:@"CONSTRACT_08"]) {
        roleName = @"检查单位实验员";
    } else if ([role isEqualToString:@"PROJECT_SUB_LEADER"]){
        roleName = @"分管领导";
    }
    roleName = [NSString stringWithFormat:@"项目切换成功! 您已成功切换到%@", roleName];
    UIView *rootView = [[UIApplication sharedApplication].delegate window].rootViewController.view;
    
    [LSUtility showToastWithMessage:roleName inView:rootView Andtime:2.5];
}

- (void)refresh {
    NSNotification *notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    
    NSNotification *notice1 = [NSNotification notificationWithName:@"Refresh_jl_jl" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice1];
    
    NSNotification *notice5 = [NSNotification notificationWithName:@"Refresh_jl_rj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice5];
    
    NSNotification *notice2 = [NSNotification notificationWithName:@"Refresh_zj_jl" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice2];
    
    NSNotification *notice3 = [NSNotification notificationWithName:@"Refresh_zj_rz" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice3];
    
    NSNotification *notice4 = [NSNotification notificationWithName:@"Refresh_zj_rj" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice4];
    NSNotification *notice6 = [NSNotification notificationWithName:@"Refresh_xjrw" object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notice6];
}



@end



